package com.lepu.app.fun.grow.calendar;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.app.application.MyApplication;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.LogUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.eyzhs.app.R;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

/**
 * 日历显示activity
 * 
 * @author Vincent Lee
 * 
 */
@SuppressLint("HandlerLeak")
public class GrowCalendarActivity extends BaseFragmentActivity implements
		View.OnClickListener, OnTopbarNewLeftLayoutListener, AsyncRequest {

	private static final String REQUEST_GET_MONTH_DATE_FIRST = "request_get_month_date_first";
	private static final String REQUEST_GET_MONTH_DATE_PRE = "request_get_month_date_pre";
	private static final String REQUEST_GET_MONTH_DATE_NEXT = "request_get_month_date_next";

	private static final int MSG_UPDATE_DATA_FIRST = 10;
	private static final int MSG_UPDATE_DATA_PRE = 20;
	private static final int MSG_UPDATE_DATA_NEXT = 30;

	private static GrowCalendarActivity mInstance = null;
	
	private GestureDetector gestureDetector = null;
	private GrowCalendarAdapter calV = null;
	private ViewFlipper flipper = null;
	private GridView gridView = null;
	private int jumpMonth = 0; // 每次滑动，增加或减去一个月,默认为0（即显示当前月）
	private int jumpYear = 0; // 滑动跨越一年，则增加或者减去一年,默认为0(即当前年)
	private int year_c = 0;
	private int month_c = 0;
	private int day_c = 0;
	private String currentDate = "";
	/** 每次添加gridview到viewflipper中时给的标记 */
	private int gvFlag = 0;
	/** 当前的年月，现在日历顶端 */
	private TextView mCurrentMonth;
	/** 上个月 */
	private LinearLayout mPreLayout;
	/** 下个月 */
	private LinearLayout mNextLayout;

	private String mCurrentYearMonthString = "";
	private JSONArray mJsonArray = null;
	private boolean mSlideLoadFlag = false;
	public String mCurrentSelectedString = "";

	@SuppressLint("SimpleDateFormat")
	public GrowCalendarActivity() {

		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
		currentDate = sdf.format(date); // 当期日期
		year_c = Integer.parseInt(currentDate.split("-")[0]);
		month_c = Integer.parseInt(currentDate.split("-")[1]);
		day_c = Integer.parseInt(currentDate.split("-")[2]);

		// 当前系统时间
		mCurrentYearMonthString = DateUtilBase.stringFromDate(new Date(),
				DateUtilBase.YEAR_MONTH);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		mNeedSwipeBack = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.grow_calendar_activity);

		mInstance = this;
		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		
		mInstance = null;
	}
	
	public static GrowCalendarActivity getInstance()
	{
		return mInstance;
	}

	private void init() {
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("相册日历");
		topbar.setonTopbarNewLeftLayoutListener(this);

		mCurrentMonth = (TextView) findViewById(R.id.currentMonth);
		mPreLayout = (LinearLayout) findViewById(R.id.preLayout);
		mNextLayout = (LinearLayout) findViewById(R.id.nextLayout);

		mPreLayout.setOnClickListener(this);
		mNextLayout.setOnClickListener(this);

		gestureDetector = new GestureDetector(this, new MyGestureListener());
		flipper = (ViewFlipper) findViewById(R.id.flipper);
		flipper.removeAllViews();

		FrameLayout okFrameLayout = (FrameLayout) findViewById(R.id.okFrameLayout);
		okFrameLayout.setOnClickListener(this);

		// init data
		requestAlbumMonthDate(0);
	}

	private void initData() {
		calV = new GrowCalendarAdapter(this, mJsonArray, getResources(),
				jumpMonth, jumpYear, year_c, month_c, day_c);
		addGridView();
		gridView.setAdapter(calV);
		flipper.addView(gridView, 0);

		addTextToTopTextView(mCurrentMonth);
	}

	private void requestAlbumMonthDate(int flag) {

		if (MyApplication.getInstance().checkIsLogin()) {
			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
			String url = Setting.getGrowMonthDateUrl();

			Map<String, Object> map = new HashMap<String, Object>();
			JSONObject params = new JSONObject();
			try {
				params.put("DeviceID", Setting.DEVICEID);
				params.put("ApplicationID", Setting.APPLICATIONID);
				params.put("UserID", loginInfo.UserID);
				params.put("LoginToken", loginInfo.LoginToken);

				params.put("Month", mCurrentYearMonthString);
			} catch (Exception e) {
			}
			map.put("ht", params);

			String request = REQUEST_GET_MONTH_DATE_FIRST;
			if (flag == 0) {
				request = REQUEST_GET_MONTH_DATE_FIRST;
			} else if (flag == 1) {
				request = REQUEST_GET_MONTH_DATE_PRE;
			} else if (flag == 2) {
				request = REQUEST_GET_MONTH_DATE_NEXT;
			}

			showProgressDialog();
			ApiClient.http_post_main(url, map, null, this, request, false);
		}
	}

	private Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_UPDATE_DATA_FIRST:

				hideProgressDialog();

				initData();
				break;
			case MSG_UPDATE_DATA_PRE:

				hideProgressDialog();

				mCurrentSelectedString = "";
				
				int flag = 0;
				if (mSlideLoadFlag) {
					flag = 0;
				} else {
					flag = gvFlag;
				}
				enterPreMonth(flag);
				break;
			case MSG_UPDATE_DATA_NEXT:

				hideProgressDialog();

				mCurrentSelectedString = "";
				
				int flag2 = 0;
				if (mSlideLoadFlag) {
					flag2 = 0;
				} else {
					flag2 = gvFlag;
				}
				enterNextMonth(flag2);
				break;

			default:
				break;
			}
		};
	};

	private class MyGestureListener extends SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			//int gvFlag = 0; // 每次添加gridview到viewflipper中时给的标记
			if (e1.getX() - e2.getX() > 120) {
				// 像左滑动
				// enterNextMonth(gvFlag);

				mSlideLoadFlag = true;
				requestEnterNextMonth();
				return true;
			} else if (e1.getX() - e2.getX() < -120) {
				// 向右滑动
				// enterPrevMonth(gvFlag);

				mSlideLoadFlag = true;
				requestEnterPreMonth();
				return true;
			}
			return false;
		}
	}

	/**
	 * 移动到上一个月
	 * 
	 * @param gvFlag
	 */
	private void enterPreMonth(int gvFlag) {
		calV = new GrowCalendarAdapter(this, mJsonArray, this.getResources(),
				jumpMonth, jumpYear, year_c, month_c, day_c);
		gridView.setAdapter(calV);
		gvFlag++;
		addTextToTopTextView(mCurrentMonth); // 移动到上一月后，将当月显示在头标题中
		flipper.addView(gridView, gvFlag);

		flipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.grow_calendar_push_right_in));
		flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.grow_calendar_push_right_out));
		flipper.showPrevious();
		flipper.removeViewAt(0);
	}

	private void requestEnterPreMonth() {
		addGridView(); // 添加一个gridView
		jumpMonth--; // 上一个月

		Date date = DateUtilBase.dateFromString(mCurrentYearMonthString,
				DateUtilBase.YEAR_MONTH);
		Date beforeDate = DateUtilBase.addDateOfMonth(date, -1);

		mCurrentYearMonthString = DateUtilBase.stringFromDate(beforeDate,
				DateUtilBase.YEAR_MONTH);

		requestAlbumMonthDate(1);
	}

	/**
	 * 移动到下一个月
	 * 
	 * @param gvFlag
	 */
	private void enterNextMonth(int gvFlag) {
		calV = new GrowCalendarAdapter(this, mJsonArray, this.getResources(),
				jumpMonth, jumpYear, year_c, month_c, day_c);
		gridView.setAdapter(calV);
		addTextToTopTextView(mCurrentMonth); // 移动到下一月后，将当月显示在头标题中
		gvFlag++;
		flipper.addView(gridView, gvFlag);
		flipper.setInAnimation(AnimationUtils.loadAnimation(this,
				R.anim.grow_calendar_push_left_in));
		flipper.setOutAnimation(AnimationUtils.loadAnimation(this,
				R.anim.grow_calendar_push_left_out));
		flipper.showNext();
		flipper.removeViewAt(0);
	}

	private void requestEnterNextMonth() {
		addGridView(); // 添加一个gridView
		jumpMonth++; // 下一个月

		Date date = DateUtilBase.dateFromString(mCurrentYearMonthString,
				DateUtilBase.YEAR_MONTH);
		Date beforeDate = DateUtilBase.addDateOfMonth(date, 1);

		mCurrentYearMonthString = DateUtilBase.stringFromDate(beforeDate,
				DateUtilBase.YEAR_MONTH);

		requestAlbumMonthDate(2);
	}

	/**
	 * 添加头部的年份 闰哪月等信息
	 * 
	 * @param view
	 */
	public void addTextToTopTextView(TextView view) {
		StringBuffer textDate = new StringBuffer();
		// draw = getResources().getDrawable(R.drawable.top_day);
		// view.setBackgroundDrawable(draw);
		textDate.append(calV.getShowYear()).append("年")
				.append(calV.getShowMonth()).append("月").append("\t");
		view.setText(textDate);
	}

	@SuppressLint("ClickableViewAccessibility")
	private void addGridView() {
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		// 取得屏幕的宽度和高度
		//WindowManager windowManager = getWindowManager();
		//Display display = windowManager.getDefaultDisplay();
		//int Width = display.getWidth();
		//int Height = display.getHeight();

		gridView = new GridView(this);
		gridView.setNumColumns(7);
//		gridView.setColumnWidth(40);
//		// gridView.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
//		if (Width == 720 && Height == 1280) {
//			gridView.setColumnWidth(40);
//		}
		gridView.setGravity(Gravity.CENTER_VERTICAL);
		gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
		// 去除gridView边框
		gridView.setVerticalSpacing(10);// 1
		gridView.setHorizontalSpacing(1);
		gridView.setOnTouchListener(new OnTouchListener() {
			// 将gridview中的触摸事件回传给gestureDetector

			public boolean onTouch(View v, MotionEvent event) {
				return GrowCalendarActivity.this.gestureDetector
						.onTouchEvent(event);
			}
		});

		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				// 点击任何一个item，得到这个item的日期(排除点击的是周日到周六(点击不响应))
				int startPosition = calV.getStartPositon();
				int endPosition = calV.getEndPosition();
				if (startPosition <= position + 7
						&& position <= endPosition - 7) {
					String scheduleDay = calV.getDateByClickItem(position)
							.split("\\.")[0]; // 这一天的阳历
					// String scheduleLunarDay =
					// calV.getDateByClickItem(position).split("\\.")[1];
					// //这一天的阴历
					String scheduleYear = calV.getShowYear();
					String scheduleMonth = calV.getShowMonth();

					String selectedDateString = scheduleYear + "-"
							+ scheduleMonth + "-" + scheduleDay;
					LogUtilBase.LogD(null, "selectedDate===>"
							+ selectedDateString);

					Date selectedDate = DateUtilBase.dateFromString(
							selectedDateString, "yyyy-M-d");
					Date sysDate = DateUtilBase.dateFromString(currentDate,
							"yyyy-M-d");

					if (selectedDate.getTime() <= sysDate.getTime()) {
						for (int i = 0; i < 42; i++) {
							LinearLayout bgLayout = (LinearLayout) gridView
									.findViewWithTag(i);
							bgLayout.setSelected(false);
						}

						LinearLayout bgLayout = (LinearLayout) gridView
								.findViewWithTag(position);
						bgLayout.setSelected(true);

						mCurrentSelectedString = DateUtilBase.stringFromDate(
								selectedDate, DateUtilBase.YEAR_MONTH_DAY);
					}else{
						UIHelper.showToast(GrowCalendarActivity.this, "请不要选择今天以后的日期");
					}

				}
			}
		});
		gridView.setLayoutParams(params);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.nextLayout: // 下一个月

			mSlideLoadFlag = false;
			// enterNextMonth(gvFlag);
			requestEnterNextMonth();
			break;
		case R.id.preLayout: // 上一个月

			mSlideLoadFlag = false;
			// enterPrevMonth(gvFlag);
			requestEnterPreMonth();

			break;
		case R.id.okFrameLayout:
			
			if(!TextUtils.isEmpty(mCurrentSelectedString))
			{
				Intent intent = new Intent();
				intent.putExtra("selected_date_string", mCurrentSelectedString);
				setResult(Activity.RESULT_OK, intent);
				
				finish(true);
			}else{
				UIHelper.showToast(GrowCalendarActivity.this, "请选择日期");
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	@Override
	public void onBackPressed() {
		finish(true);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_GET_MONTH_DATE_FIRST)
				|| object.equals(REQUEST_GET_MONTH_DATE_PRE)
				|| object.equals(REQUEST_GET_MONTH_DATE_NEXT)) {

			try {
				JSONObject jsonObject = new JSONObject((String) data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				mJsonArray = (JSONArray) obj1.get("ListInfo");
			} catch (JSONException e) {
				e.printStackTrace();
			}

			if (object.equals(REQUEST_GET_MONTH_DATE_FIRST)) {
				mHandler.sendEmptyMessage(MSG_UPDATE_DATA_FIRST);
			} else if (object.equals(REQUEST_GET_MONTH_DATE_PRE)) {
				mHandler.sendEmptyMessage(MSG_UPDATE_DATA_PRE);
			} else if (object.equals(REQUEST_GET_MONTH_DATE_NEXT)) {
				mHandler.sendEmptyMessage(MSG_UPDATE_DATA_NEXT);
			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_GET_MONTH_DATE_FIRST)) {
			mHandler.sendEmptyMessage(MSG_UPDATE_DATA_FIRST);
		} else if (object.equals(REQUEST_GET_MONTH_DATE_PRE)) {
			mHandler.sendEmptyMessage(MSG_UPDATE_DATA_PRE);
		} else if (object.equals(REQUEST_GET_MONTH_DATE_NEXT)) {
			mHandler.sendEmptyMessage(MSG_UPDATE_DATA_NEXT);
		}
	};

}